# crawler/xhs_login.py
import requests
from playwright.sync_api import sync_playwright

def login_and_get_cookies():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()

        page.goto('https://www.xiaohongshu.com/web/login')

        print("请扫描二维码登录...")
        while True:
            if "登录成功" in page.content():
                break

        cookies = context.cookies()
        browser.close()

        return cookies

def save_cookies(cookies, file_path='cookies.txt'):
    with open(file_path, 'w') as f:
        for cookie in cookies:
            f.write(f"{cookie['name']}={cookie['value']}\n")

if __name__ == '__main__':
    cookies = login_and_get_cookies()
    save_cookies(cookies)
    print("Cookie 保存成功")